﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace NetworkCrashSimulator.Core
{
    public enum ActionError : short
    {
        NoError = 0,
        UnableToCrash = 1,
        UnableToRestore = 2,
        UnableToList = 3,
        AdapterNotFound = 4,
        AdapterConfigurationNotSupported = 5,
        ConfigurationFileNotFound = 6,
        UnableToCreateConfigurationFile = 7
    }

    public class Actions
    {
        /// <summary>
        /// File name for the file that will hold the network adapter configuration.
        /// </summary>
        const string saveFileName = "AdapterConfig.ncs";

        /// <summary>
        /// Generate a console line following the application template.
        /// </summary>
        /// <param name="message">Message to show on the console line.</param>
        /// <remarks>Date and time will appear in the console line.</remarks>
        internal static void GenerateConsoleLine(string message)
        {
            GenerateConsoleLine(message, true);
        }

        /// <summary>
        /// Generate a console line following the application template.
        /// </summary>
        /// <param name="message">Message to show on the console line.</param>
        /// <param name="addDateTime">Date time should be added to the console line?</param>
        internal static void GenerateConsoleLine(string message, bool addDateTime)
        {
            if (addDateTime)
            {
                message = string.Format("[{0}] {1}", DateTime.Now.ToString(), message);
            }

            Console.WriteLine(message);
        }

        /// <summary>
        /// Crash a specific network adapter.
        /// </summary>
        /// <param name="adapterName">Name of the network adapter.</param>
        /// <returns>Error for the action.</returns>
        public static ActionError CrashAdapter(string adapterName)
        {
            return CrashAdapter(adapterName, false);
        }


        /// <summary>
        /// Crash a specific network adapter.
        /// </summary>
        /// <param name="adapterName">Name of the network adapter.</param>
        /// <returns>Error for the action.</returns>
        public static ActionError CrashAdapter(string adapterName, bool forceSave)
        {
            ActionError error = ActionError.NoError;

            Core.NetworkAdapterConfiguration.NetworkAdapterConfigurationCollection networkAdapters = Core.NetworkAdapterConfiguration.GetInstances("Description = '" + adapterName + "'");

            if (networkAdapters.Count == 1)
            {
                foreach (Core.NetworkAdapterConfiguration networkAdapter in networkAdapters)
                {
                    CrashAdapter(networkAdapter, forceSave);
                }
            }
            else
            {
                error = ActionError.AdapterNotFound;
                GenerateConsoleLine("Network adapter not found.");
            }

            return error;
        }

        /// <summary>
        /// Crash a specific network adapter.
        /// </summary>
        /// <param name="networkAdapter">Network adapter object.</param>
        /// <returns>Error for the action.</returns>
        private static ActionError CrashAdapter(Core.NetworkAdapterConfiguration networkAdapter, bool forceSave)
        {
            ActionError error = ActionError.NoError;

            Actions.GenerateConsoleLine(string.Empty, false);

            GenerateConsoleLine("Trying to crash network adapter " + networkAdapter.Description + ".");
            try
            {
                if (networkAdapter.DHCPEnabled)
                {
                    networkAdapter.ReleaseDHCPLease();
                }
                else
                {
                    if (forceSave)
                    {
                        error = SaveSettings(networkAdapter);
                    }
                    string[] newIPAddress = { "169.254.0.10" };
                    string[] newIPSubnet = { "255.255.0.0" };
                    string[] newDefaultIPGateway = { "127.0.0.1" };
                    ushort[] newGatewayCostMetric = { 1 };
                    networkAdapter.EnableStatic(newIPAddress, newIPSubnet);
                    networkAdapter.SetGateways(newDefaultIPGateway, newGatewayCostMetric);
                }
                GenerateConsoleLine("Network adapter crashed successfully.");
            }
            catch (Exception ex)
            {
                error = ActionError.UnableToCrash;
                GenerateConsoleLine("Problems crashing the network adapter: " + ex.Message);
            }

            return error;
        }

        /// <summary>
        /// Repair a specific network adapter.
        /// </summary>
        /// <param name="adapterName">Name of the network adapter.</param>
        /// <returns>Error for the action.</returns>
        public static ActionError RepairAdapter(string adapterName)
        {
            ActionError error = ActionError.NoError;

            Core.NetworkAdapterConfiguration.NetworkAdapterConfigurationCollection networkAdapters = Core.NetworkAdapterConfiguration.GetInstances("Description = '" + adapterName + "'");

            if (networkAdapters.Count == 1)
            {
                foreach (Core.NetworkAdapterConfiguration networkAdapter in networkAdapters)
                {
                    RepairAdapter(networkAdapter);
                }
            }
            else
            {
                error = ActionError.AdapterNotFound;
                GenerateConsoleLine("Network adapter not found.");
            }

            return error;
        }

        /// <summary>
        /// Repair a specific network adapter.
        /// </summary>
        /// <param name="networkAdapter">Network adapter object.</param>
        /// <returns>Error for the action.</returns>
        private static ActionError RepairAdapter(NetworkAdapterConfiguration networkAdapter)
        {
            ActionError error = ActionError.NoError;

            Actions.GenerateConsoleLine(string.Empty, false);

            GenerateConsoleLine("Trying to repair network adapter " + networkAdapter.Description + ".");
            try
            {
                if (networkAdapter.DHCPEnabled)
                {
                    networkAdapter.RenewDHCPLease();
                }
                else
                {
                    try
                    {
                        SaveInformation saveInformation;
                        error = LoadSettings(out saveInformation);
                        networkAdapter.EnableStatic(saveInformation.IPAddress, saveInformation.IPSubnet);
                        networkAdapter.SetGateways(saveInformation.DefaultIPGateway, saveInformation.GatewayCostMetric);

                    }
                    catch
                    {
                        GenerateConsoleLine("Unable to load the network adapter configurations.");
                    }
                }
                GenerateConsoleLine("Network adapter repaired successfully.");

            }
            catch (Exception ex)
            {
                error = ActionError.UnableToRestore;
                GenerateConsoleLine("Problems repairing the network adapter: " + ex.Message);
            }

            return error;
        }

        /// <summary>
        /// List available network adapter for the console.
        /// </summary>
        /// <returns>Error for the action.</returns>
        public static ActionError ListAdaptersConsole()
        {
            ActionError error = ActionError.NoError;

            try
            {
                NetworkAdapterConfiguration.NetworkAdapterConfigurationCollection networkAdaptersConfigurations = ListAdapters();

                if (networkAdaptersConfigurations.Count > 0)
                {
                    GenerateConsoleLine(String.Empty, false);
                    GenerateConsoleLine("Listing available network adapters:", false);
                    GenerateConsoleLine(String.Empty, false);
                    short counting = 1;
                    foreach (NetworkAdapterConfiguration networkAdapterConfiguration in networkAdaptersConfigurations)
                    {
                        GenerateConsoleLine("   " + counting.ToString() + ". " + networkAdapterConfiguration.Description, false);
                        counting++;
                    }
                }
                else
                {
                    GenerateConsoleLine("No network adapter available.");
                }

            }
            catch (Exception ex)
            {
                error = ActionError.UnableToRestore;
                GenerateConsoleLine("Problems listing network adapters: " + ex.Message);
            }

            return error;
        }

        /// <summary>
        /// List available network adapter for the console.
        /// </summary>
        /// <returns>List of the available adapters.</returns>
        public static NetworkAdapterConfiguration.NetworkAdapterConfigurationCollection ListAdapters()
        {
            return NetworkAdapterConfiguration.GetInstances();
        }

        private static ActionError SaveSettings(NetworkAdapterConfiguration networkAdapter)
        {
            try
            {
                SaveInformation saveInformation = new SaveInformation();
                saveInformation.IPAddress = networkAdapter.IPAddress;
                saveInformation.IPSubnet = networkAdapter.IPSubnet;
                saveInformation.DefaultIPGateway = networkAdapter.DefaultIPGateway;
                saveInformation.GatewayCostMetric = networkAdapter.GatewayCostMetric;

                string actualPath = Environment.CurrentDirectory;
                string savePath = actualPath + "\\" + saveFileName;

                if (File.Exists(savePath))
                {
                    File.Delete(savePath);
                }

                Stream stream = File.Open(savePath, FileMode.Create);
                BinaryFormatter binaryFormatter = new BinaryFormatter();

                binaryFormatter.Serialize(stream, saveInformation);

                stream.Close();

                return ActionError.NoError;
            }
            catch
            {

                return ActionError.UnableToCreateConfigurationFile;
            }
        }

        private static ActionError LoadSettings(out SaveInformation saveInformation)
        {
            saveInformation = null;

            try
            {
                string actualPath = Environment.CurrentDirectory;
                string savePath = actualPath + "\\" + saveFileName;

                Stream stream = File.Open(savePath, FileMode.Open);
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                saveInformation = (SaveInformation)binaryFormatter.Deserialize(stream);
                stream.Close();

                return ActionError.NoError;
            }
            catch
            {
                return ActionError.ConfigurationFileNotFound;
            }
        }

        public static void TimedCrash(string adapterName, int totalTime, int crashes, int timeToRecover)
        {
            ActionError error = ActionError.NoError;

            Core.NetworkAdapterConfiguration.NetworkAdapterConfigurationCollection networkAdapters = Core.NetworkAdapterConfiguration.GetInstances("Description = '" + adapterName + "'");

            if (networkAdapters.Count == 1)
            {
                foreach (Core.NetworkAdapterConfiguration networkAdapter in networkAdapters)
                {
                    if (!networkAdapter.DHCPEnabled)
                    {
                        SaveSettings(networkAdapter);
                    }
                }
            }
            else
            {
                error = ActionError.AdapterNotFound;
                GenerateConsoleLine("Network adapter not found.");
            }

            if (error == ActionError.NoError)
            {
                Core.TimedCrash timedCrash = new Core.TimedCrash();
                timedCrash.Execute(adapterName, totalTime, crashes, timeToRecover);
            }
        }
    }
}
